let preNavSelect = $(".nav > a.photo_album");
const aDoms = $(".nav > a:not(.navbar-brand)");
const createPhotoalbum = $(".create-photoalbum");//创建相册
const uploadPhotoInput = $(".main > header > input[type=file]");
const uploadPhoto = $(".upload-photo");//上传照片
let preLeftSelectItem = $(".defaultAll > a");
const count = 2;//每页显示的照片数
let currentPage = 1;

// const albumTem = `
// <li class="list-group-item d-flex justify-content-between align-items-center">
//    <a></a>
//    <button type="button" class="close" aria-label="Close">
//      <span aria-hidden="true">&times;</span>
//    </button>
//  </li>
// `;

//左侧item模板
function getLeftAlbumTem(name) {
  return `
   <li class="list-group-item d-flex justify-content-between align-items-center">
      <a>${name}</a>
      <button type="button" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </li>
 `
}

//图片模板
function imgTem(url) {
  return `
  <div class="card" style="width: 13rem; margin:1;max-height:13rem">
    <img class="card-img-top" src="${url}" alt="Card image cap">
    <div class="card-body text-center" style="margin:0;padding:0;">
      <a href="#" class="btn btn-primary" style="margin:0;padding:4;width:100%;line-height:23px;background-color:rgba(0,0,0,0.5 )">delete</a>
    </div>
  </div>
  `;
}

//顶部点击
clickNav();
//创建相册
createalbum();
//设置左边框点击事件
setListener();
//添加图片
clickUploadPhoto();
//刷新
getDefaultAlbum();


//刷新
function getDefaultAlbum() {
  $.get("/album", res => {
    currentPage = 1;
    if (preLeftSelectItem.text() !== "全部") {
      preLeftSelectItem.parent().css("background-color", "white");
    }
    preLeftSelectItem = $(".defaultAll > a");
    preLeftSelectItem.parent().css("background-color", "SkyBlue");
    setUrl(res.albumMap.arr, res.totalNum);
    renderAlbumList(res.albumNames);
  })
}

//添加照片
function clickUploadPhoto() {
  uploadPhoto.click(e => {
    uploadPhotoInput.click();
  })
}
function createReader(e) {
  let formData = new FormData();
  formData.append("name", preLeftSelectItem.text());
  let files = e.target.files;
  for (var file of files) {
    formData.append("mfiles", file);
  }
  uploadImage(formData);
  uploadPhotoInput.val("");
}
function uploadImage(formData){
  fetch("/album/addphoto",{
             method:"POST",
             body:formData
         }).then(res => res.json())
           .then(res => {
             currentPage = Math.ceil(res.totalNum/count);
           setUrl(res.albumMap.arr, res.totalNum);
         })
  }

  //加载设置照片
function setUrl(files, totalNum) {
  console.log("seturl");
  $(".photo_container").html("");
  renderPagination(totalNum);
  if (!files || files.length == 0) {
    return;
  }
  for (var file of files) {
    let url = "/album/img/" + file.filename;
    $(".photo_container").append($(imgTem(url)));
  }
  addPhotoDelListener();
}

function addPhotoDelListener() {
  let params = {};
  $(".card-body").unbind("click");
  $(".card-body").click(e => {
    if (confirm("删除照片？")) {
      let strs = ($(e.target).parent().prev().attr("src")).split("/");
      let filename = strs[strs.length-1];
      params.name = preLeftSelectItem.text();
      params.filename = filename;
      $.post("/album/deletephoto", params, res => {
        $(e.target).parent().parent().remove();
         preLeftSelectItem.click();
      });
    }
  })
}

//设置分页
function renderPagination(totalNum) {
  let pages = Math.ceil(totalNum/count);
  $(".pagination").html("");
  if (pages <= 0) {
    return;
  }
  let prePage = currentPage<=1 ? 1 : Number(currentPage) -1;
  let nextPage = currentPage >= pages ? pages:Number(currentPage)+1;
  $(".pagination").append($(`<li class="page-item"><a class="page-link" data-page="${prePage}" href="${getUrl(prePage)}">Prev</a></li>`));
  for (var i = 1; i <= pages; i++) {
    if (currentPage == i) {
      $(".pagination").append($(`<li class="page-item active"><a class="page-link" data-page="${i}" href="${getUrl(i)}">${i}</a></li>`));
    }else {
      $(".pagination").append($(`<li class="page-item"><a class="page-link" data-page="${i}" href="${getUrl(i)}">${i}</a></li>`));

    }
  }
  $(".pagination").append($(`<li class="page-item"><a class="page-link" data-page="${nextPage}" href="${getUrl(nextPage)}">Next</a></li>`));

  setListenerPages();
}
function setListenerPages() {
  $(".page-item").click(e => {
    currentPage = $(e.target).attr("data-page");
    console.log("page = " , currentPage);
    e.preventDefault();
    $.get(e.target.href, res => {
      setUrl(res.albumMap.arr, res.totalNum);
    })
  })
}

function getUrl(page){
  return `/album/selectpage?page=${page}&name=${preLeftSelectItem.text()}`;
}

//创建相册
function createalbum(){
  createPhotoalbum.click(function(event) {
    var result = window.prompt("请输入相册名字", "");
    if (result === null) {
      return;
    }
    if (!result) {
      alert("名字不能为空！")
    }else{
      addAlbum(result);
    }
  });
}
//添加相册
function addAlbum(name){
  $.post("/album/createalbum", {name}, res => {
    if (res) {
      alert(res.error);
    }else {
      $(".left").append($(getLeftAlbumTem(name)));//创建的相册边栏
      let leftItemDom = $(".left > li:last-of-type");
      leftItemDom.addClass(name);
      setListener();
      addDeleteListener();
    }
  })
}

//设置相册点击监听
function setListener() {
  $(".left > .list-group-item > a").unbind("click");
  $(".left > .list-group-item > a").click(e => {
    let params = {};
    if (preLeftSelectItem) {
      preLeftSelectItem.parent().css("background-color", "white");
    }
    $(e.target).parent().css("background-color", "SkyBlue");
    preLeftSelectItem = $(e.target);
    params.name = preLeftSelectItem.text();
    $.get("/album/albumgetitem", params, res => {//6228270016026616375
      currentPage = 1;
      setUrl(res.albumMap.arr, res.totalNum);
    })
  });
}

function addDeleteListener() {
  $(".left > .list-group-item > button").unbind("click");
  let params = {};
  $(".left > .list-group-item > button").click(e => {
    if (confirm("确认删除?")) {
      params.name = $(e.target).parent().prev().text();
      $.post("/album/deletealbum", params, res => {
        $(e.target).parent().parent().remove();
       if (params.name == preLeftSelectItem.text()) {
         $(".left > li:first-child > a").click();
       }
      });
    }
  })
}

//顶部点击
function clickNav() {
  aDoms.click(function (e) {
    if (preNavSelect) {
      preNavSelect.removeClass("disabled")
    }
    $(e.target).addClass("disabled");
    preNavSelect = $(e.target);
  })
}

function renderAlbumList(albumNames) {
  for (obj of albumNames) {
    const name = obj.name;
    $(".left").append($(getLeftAlbumTem(name)));
    let leftItemDom = $(".left > li:last-of-type");
    leftItemDom.addClass(name);
  }
  setListener();
  addDeleteListener();
}
